﻿using System;
using System.Linq;
using System.Xml.Linq;
using IDeal.Models;
using IDeal.Services;

namespace IDeal.Serialization
{
    internal class DirectoryResponseXmlReader : XmlMessageReader<DirectoryResponse>
    {
        public DirectoryResponseXmlReader(IIDealServices iDealServices) : base(iDealServices)
        {
        }

        protected override void ParseRootElement(DirectoryResponse instance, XElement rootElement)
        {
            var directoryElement = rootElement.Element(Ns + "Directory");
            var directory = new IssuersDirectory();

            instance.Directory = directory;
            instance.AcquirerId = rootElement.Element(Ns + "Acquirer").Element(Ns + "acquirerID").Value;
            directory.TimeStamp = DateTime.Parse(directoryElement.Element(Ns + "directoryDateTimeStamp").Value);

            var issuers = directoryElement.Elements(Ns + "Issuer")
                .Select(x => new Issuer
                {
                    Id = x.Element(Ns + "issuerID").Value,
                    Name = x.Element(Ns + "issuerName").Value,
                    ListType = (IssuerListType)Enum.Parse(typeof(IssuerListType), x.Element(Ns + "issuerList").Value)
                });

            foreach (var issuer in issuers)
            {
                instance.Directory.Issuers.Add(issuer);
            }
        }
    }
}
